import { logout } from '@/utils';
import axios, { AxiosRequestConfig } from 'axios';
import { Notification } from '@arco-design/web-react';
import { server } from '@/config';

const instance = axios.create({
  baseURL: `http${server.safe}://${server.baseURL}/`,
  timeout: 100000,
});

const getRes = (a: any, b: any) => {
  let res: any = {};
  if (b?.constructor.name === 'File') {
    return b;
  }
  if (!a && !b) {
    return res;
  }
  if (a && !b) {
    res = a;
  } else if (!a && b) {
    res = b;
  } else {
    res = Object.assign(a, b);
  }
  return res;
};

export const request =
  <D>(config: AxiosRequestConfig<D>) =>
  async (data?: any, params?: any) => {
    try {
      let token = {};
      const loginParams = JSON.parse(localStorage.getItem('loginParams'));
      if (loginParams) {
        const {
          saTokenInfo: { tokenName, tokenValue },
        } = loginParams;
        token = {
          [tokenName]: tokenValue,
        };
      }
      const requestRes = await instance({
        ...config,
        data: getRes(config?.data, data),
        params: getRes(config?.params, params),
        headers: {
          ...token,
          'Access-Control-Allow-Origin': '*',
          ...config?.headers,
        },
      });

      // console.log('requestRes', requestRes);

      if (requestRes.config?.responseType === 'blob') {
        return requestRes.data;
      }

      // 如果成功返回数据
      if (requestRes.data?.success) {
        return requestRes.data;
      }
      // 如果失败
      // errorCode等于A0330 返回登录页从新登录
      if (requestRes.data?.errorCode === 'A0330') {
        Notification.warning({
          title: '提示',
          content: requestRes.data.errorMessage,
        });
        // logout();
      }
    } catch (error) {
      Notification.error({
        title: '请求失败',
        content: error.message,
      });
      throw error;
    }
  };
